package org.mmw.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.mmw.common.JwtHelper;
import org.mmw.common.Result;
import org.mmw.entity.User;
import org.mmw.service.UserService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/system/person")
@Api(tags = "登录接口")
public class LoginController {


    @Resource
    UserService userService;


    @PostMapping("/login")
    @ApiOperation(value = "登录")
    public Result login(@RequestParam String username,@RequestParam String password){
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            return Result.build(null,"用户名或密码为空",40001);
        }

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,username);
        User isHaveUser = userService.getOne(wrapper);
        if (isHaveUser == null){
            return Result.build(null,"用户名不存在",40002);
        }
        wrapper.eq(User::getPassWord,password);
        User user = userService.getOne(wrapper);
        if (user == null){
            return Result.build(null,"密码错误",40003);
        }

        String token = JwtHelper.createToken(user.getId(), user.getUserName());

        Map<String,Object> res = new HashMap<>();
        res.put("username",user.getUserName());
        res.put("token",token);

        return Result.build(res,"登陆成功",200);
    }

    @PostMapping("/register")
    @ApiOperation(value = "注册")
    public Result register(@RequestBody User user){
        String username = user.getUserName();
        String password = user.getPassWord();

        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            return Result.build(null,"用户名或密码为空",40001);
        }

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,username);
        User isHaveUser = userService.getOne(wrapper);
        if (isHaveUser != null){
            return Result.build(null,"用户名已存在",40004);
        }

        User user1 = new User();
        user1.setUserName(username);
        user1.setPassWord(password);

        userService.save(user1);
        return Result.build(null,"注册成功",200);
    }
}
